package com.alibaba.middleware.hsf.optihessian;

import com.alibaba.middleware.hsf.Data;
import com.alibaba.middleware.hsf.guide.api.model.OrderModel;

import com.taobao.hsf.com.caucho.hessian.io.HSFHessian2Input;
import com.taobao.hsf.com.caucho.hessian.io.HSFHessian2Output;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author weipeng2k 2017年12月27日 上午11:06:08
 */
@State(Scope.Benchmark)
public class DeserialPerf {

    static ArrayList<HSFHessian2Input.ObjectDefinition> objectDefinitions = new ArrayList<HSFHessian2Input.ObjectDefinition>();
    byte[] content;

    @Setup
    public void init() {
        OrderModel orderModel = Data.gen();
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            HSFHessian2Output out = new HSFHessian2Output(baos, SerialPerf.identityIntMap);
            out.writeObject(orderModel);
            out.flush();
            content = baos.toByteArray();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

        ByteArrayInputStream bais = new ByteArrayInputStream(content);
        HSFHessian2Input in = new HSFHessian2Input(objectDefinitions, bais);
        try {
            in.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            HSFHessian2Output out = new HSFHessian2Output(baos, SerialPerf.identityIntMap);
            out.writeObject(orderModel);
            out.flush();
            content = baos.toByteArray();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    public void deserial() throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(content);
        HSFHessian2Input in = new HSFHessian2Input(objectDefinitions, bais);
        in.readObject();
    }

}
